from flask import render_template,g, redirect,url_for,request,current_app, jsonify

from info.modules.profile import profile_blu
from info.utils.common import login_required
from info import db
from info.utils.response_code import RET



@profile_blu.route('/info')
@login_required
def get_user_info():
    user = g.user

    if not user:
        return redirect(url_for('index.index'))

    data = {
        'user_info':user.to_dict()
    }
    return render_template('news/user.html',data=data)


@profile_blu.route('/user_info',methods=["GET","POST"])
@login_required
def user_base_info():
    user = g.user
    if request.method =="POST":
        json_data = request.json
        nick_name = json_data.get("nick_name")
        signature = json_data.get("signature")
        gender = json_data.get("gender")

        if not all([nick_name,signature,gender]):
            return jsonify(errno=RET.PARAMERR,errmsg="参数不全")
        if gender not in ["MAN","WOMAN"]:
            return jsonify(errno=RET.PARAMERR,errmsg="参数不全")

        user.nick_name = nick_name
        user.gender = gender
        user.signature =signature

        try:
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            db.session.rollback()
            return jsonify(errno=RET.DBERR,errmsg="数据保存失败")
        return jsonify(errno=RET.OK,errmsg="更新成功")


    data ={
        "user_info":user.to_dict()
    }

    return render_template("news/user_base_info.html",data = data)
